package top.lileix.example.netty.chat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

public class ChatServerHandler extends SimpleChannelInboundHandler<String> {
	Logger logger = LoggerFactory.getLogger(getClass());
	public static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		ctx.write("链接服务器，你的id是" + ctx.channel().id().asShortText() + "\r\n");
		ctx.flush();
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
		Channel incoming = ctx.channel();
		for (Channel channel : channels) {
			if (channel != incoming) {
				channel.writeAndFlush("给" + channel.id().asShortText() + "推送消息:" + msg + "\r\n");
			} else {
				channel.writeAndFlush("发送" + msg + "成功，推送" + (channels.size() - 1) + "个客户端\n");
			}
		}
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception { // (6)
		Channel incoming = ctx.channel();
		logger.debug("客户端:{}掉线", incoming.id().asShortText());
	}

	// --------------------------------
	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		Channel incoming = ctx.channel();
		// for (Channel channel : channels) {
		// channel.writeAndFlush("[系统消息] - " + incoming.id().asShortText() + "
		// 加入\n");
		// }
		logger.debug("{}链接服务器 ", incoming.id().asShortText());
		channels.add(ctx.channel());
	}

	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		Channel incoming = ctx.channel();
		// for (Channel channel : channels) {
		// channel.writeAndFlush("[系统消息] - " + incoming.id().asShortText() + "
		// 离开\n");
		// }
		logger.debug("{}断开服务器 ", incoming.id().asShortText());
		channels.remove(ctx.channel());
	}
}
